import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../role_view_model.dart';
import 'permission_group_model.dart';
import 'role_permissions_view_model.dart';

class RolePermissionsView extends StatelessWidget {
  final int roleId;
  final String roleName;

  const RolePermissionsView({
    Key? key,
    required this.roleId,
    required this.roleName,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => RolePermissionsViewModel(RoleViewModel())..loadPermissions(roleId),
      child: _RolePermissionsContent(roleName: roleName, roleId: roleId),
    );
  }
}

class _RolePermissionsContent extends StatelessWidget {
  final String roleName;
  final int roleId;

  const _RolePermissionsContent({
    Key? key,
    required this.roleName,
    required this.roleId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$roleName - 权限管理'),
        actions: [
          Consumer<RolePermissionsViewModel>(
            builder: (context, viewModel, child) {
              return TextButton(
                onPressed: viewModel.isLoading
                    ? null
                    : () async {
                        final success = await viewModel.savePermissions(roleId);
                        if (success && context.mounted) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('权限保存成功')),
                          );
                          Navigator.of(context).pop();
                        }
                      },
                child: const Text('保存', style: TextStyle(color: Colors.white)),
              );
            },
          ),
        ],
      ),
      body: Consumer<RolePermissionsViewModel>(
        builder: (context, viewModel, child) {
          if (viewModel.isLoading) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('正在加载权限数据...'),
                ],
              ),
            );
          }

          if (viewModel.error != null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.error_outline, color: Colors.red, size: 48),
                  const SizedBox(height: 16),
                  Text(
                    viewModel.error!,
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton.icon(
                    onPressed: () => viewModel.loadPermissions(roleId),
                    icon: const Icon(Icons.refresh),
                    label: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          final groups = viewModel.permissionGroups;
          if (groups.isEmpty) {
            return const Center(
              child: Text('暂无可用的权限数据'),
            );
          }

          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: groups.map((group) {
                return Card(
                  margin: const EdgeInsets.only(bottom: 16),
                  child: Theme(
                    data: Theme.of(context).copyWith(
                      dividerColor: Colors.transparent,
                    ),
                    child: ExpansionTile(
                      initiallyExpanded: true,
                      title: Row(
                        children: [
                          Checkbox(
                            value: group.rootPermission.isSelected,
                            onChanged: (bool? value) {
                              viewModel.updatePermission(
                                group.rootPermission.id,
                                value ?? false,
                                isRootPermission: true,
                              );
                            },
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(group.name),
                                if (group.remark.isNotEmpty)
                                  Text(
                                    group.remark,
                                    style: Theme.of(context).textTheme.bodySmall,
                                  ),
                              ],
                            ),
                          ),
                          Text(
                            '(${group.permissions.length})',
                            style: Theme.of(context).textTheme.bodySmall,
                          ),
                        ],
                      ),
                      children: group.permissions.map((permission) {
                        return Padding(
                          padding: const EdgeInsets.only(left: 16),
                          child: CheckboxListTile(
                            title: Text(permission.name),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(permission.remark),
                                Text('权限代码: ${permission.code}', 
                                    style: Theme.of(context).textTheme.bodySmall),
                              ],
                            ),
                            value: permission.isSelected,
                            onChanged: (bool? value) {
                              viewModel.updatePermission(permission.id, value ?? false);
                            },
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                );
              }).toList(),
            ),
          );
        },
      ),
    );
  }
}
